package com.imooc.qrcode;

import com.swetake.util.Qrcode;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;

/**
 * Created by Administrator on 2017/8/14.
 */
public class CreateQRCode {
    public static void main(String[] args) throws Exception {

        // 使用QRCode进行绘制二维码
        Qrcode x = new Qrcode();
        x.setQrcodeErrorCorrect('M');// 纠错等级
        x.setQrcodeEncodeMode('B');// N代表数字，A代表a-Z，B代表其他字符
        x.setQrcodeVersion(7);// 版本
        int width = 67 + 12 * (7 - 1);// 计算宽高有一个公式  67 + 12 * (版本号 - 1)
        int heigh = 67 + 12 * (7 - 1);

        //String qrData = "我是中国人！";
        String qrData = "http://www.baidu.com";

        BufferedImage bufferedImage = new BufferedImage(width, heigh, BufferedImage.TYPE_INT_RGB);

        Graphics2D gs = bufferedImage.createGraphics();
        gs.setBackground(Color.WHITE);
        gs.setColor(Color.BLACK);
        gs.clearRect(0, 0, width, heigh);

        int pixoff = 2;//偏移量

        //byte[] d = qrData.getBytes("gb2312");// 中文加上转码
        byte[] d = qrData.getBytes();
        if (d.length > 0 && d.length < 120) {
            boolean[][] s = x.calQrcode(d);
            for (int i = 0; i < s.length; i++) {
                for (int j = 0; j < s.length; j++) {
                    if (s[j][i]) {
                        gs.fillRect(j * 3 + pixoff, i * 3 + pixoff, 3, 3);
                    }
                }
            }
        }

        gs.dispose();
        bufferedImage.flush();
        ImageIO.write(bufferedImage,"png",new File("D:/code/qrcodeLink.png"));
    }
}
